package times

import (
	"fmt"
	"strconv"
	"time"
)

type Format struct {
	datetime string
	zone     string
}

func (d Format) parse() (time.Time, error) {
	location := ""
	if d.zone == "" {
		location = "Asia/Shanghai"
	}
	zone, _ := time.LoadLocation(location)
	return time.ParseInLocation("2006-01-02 15:04:05", d.datetime, zone)
}

func (d Format) Date(parameter ...string) string {

	datetime, err := d.parse()

	if err != nil {
		return ""
	}

	sp := "-"
	if len(parameter) > 0 {
		sp = parameter[0]
	}

	return fmt.Sprintf("%d%s%s%s%s", datetime.Year(), sp, PadTwoDigit(int(datetime.Month())), sp, PadTwoDigit(datetime.Day()))
}

func (d Format) Time(parameter ...string) string {

	datetime, err := d.parse()

	if err != nil {
		return ""
	}

	sp := ":"
	if len(parameter) > 0 {
		sp = parameter[0]
	}

	return fmt.Sprintf("%d%s%s%s%s", datetime.Hour(), sp, PadTwoDigit(int(datetime.Minute())), sp, PadTwoDigit(datetime.Second()))
}

func (d Format) DateTime(parameter ...string) string {

	sp := " "
	if len(parameter) > 0 {
		sp = parameter[0]
	}

	return d.Date() + sp + d.Time()
}

func (d Format) Unix() int64 {
	datetime, err := d.parse()

	if err != nil {
		return 0
	}
	return datetime.Unix()
}

// Parse Format time, support string and time.Time
// times.Parse("2022-02-01 10:45:15").Date()
// times.Parse(time.Now()).Date()
func Parse(parameter interface{}) *Format {
	datetime := ""
	if val, ok := parameter.(string); ok {
		datetime = val
	} else if val1, okk := parameter.(time.Time); okk {
		datetime = val1.Format("2006-01-02 15:04:05")
	}
	return &Format{
		datetime: datetime,
	}
}

// PadTwoDigit Convert to two digits
func PadTwoDigit(number int) string {
	str := ""
	if number < 10 {
		str = "0"
	}
	return str + strconv.Itoa(number)
}
